package com.cloud_disk.controller;

import com.cloud_disk.service.impl.CloudFileServiceImpl;
import com.cloud_disk.service.impl.LinkInfoServiceImpl;
import com.cloud_disk.vo.File;
import com.cloud_disk.vo.ShareFileLinkInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.util.List;

/**
 * @author 徐华星
 * 日期 2021/12/21
 */
@Controller
@RequestMapping("/share")
public class ShareLinkController {

    @Autowired
    private LinkInfoServiceImpl linkInfoService;

    @Autowired
    private CloudFileServiceImpl fileService;

    @RequestMapping("/index")
    public String index(){
        return "/share/index";
    }

    @RequestMapping("/list")
    public String list(Integer userid,ModelMap map){

        List<ShareFileLinkInfo> linkInfoList = linkInfoService.getAllShareLinkByUserId(userid);

        map.put("infolist",linkInfoList);


        return "/share/list";
    }

    //测试创建链接页面
    @RequestMapping("/create")
    public String createLink(ModelMap map){
        String url = linkInfoService.createLink(0,3,1,1);
        map.put("msg","链接为：localhost:8080/share/link/"+url);
        return "/share/index";
    }

    //修改前
    @RequestMapping("/modifyForm")
    public String modifyLinkByIdForm(Integer id,ModelMap map){
        map.put("id",id);
        return "/share/modifyForm";
    }

    //修改后
    @RequestMapping("/modify")
    public String modify(Integer id,Integer lifetime){
        linkInfoService.modifyLinkInfoLivetimeByID(id,lifetime);
        ShareFileLinkInfo info = linkInfoService.getLinkInfoById(id);
        return "redirect:/share/list?userid="+info.getUserid();
    }

    //删除链接
    @RequestMapping("/deleteLink")
    public String deleteLinkInfoByid(Integer id){
        Integer userid = linkInfoService.getLinkInfoById(id).getUserid();
        linkInfoService.deleteLinkInfoByID(id);
        return "redirect:/share/list?userid="+userid;
    }


    //访问分享的文件
    @RequestMapping("/link/{url}")
    public String link(@PathVariable String url, ModelMap map){
        ShareFileLinkInfo info = linkInfoService.getLinkInfoByURL(url);

        //链接不存在，分享的文件不存在，链接过期
        if(info==null){
            map.put("msg","链接不存在...");
            return "/share/index";
        }else if(fileService.getFileByFileId(info.getFileid())==null){
            map.put("msg","分享的文件不见了...");
            return "/share/index";
        }else if(info.getStarttime().compareTo(info.getLivetime())>=0){
            map.put("msg","链接已过期...");
            return "/share/index";
        }

        File file = fileService.getFileByFileId(info.getFileid());

        if(!info.getPassword().equals("")){
            map.put("url",url);
            map.put("msg","");
            return "/share/links";
        }
        map.put("info",info);
        map.put("filename", file.getFilename());
        return "/share/link";
    }

    //访问带密码密分享的文件
    @RequestMapping("/links")
    public String links(String url,String password, ModelMap map){
        ShareFileLinkInfo info = linkInfoService.getLinkInfoByURL(url);
        File file = fileService.getFileByFileId(info.getFileid());

        if(info.getPassword().equals(password)) {
            map.put("info",info);
            map.put("filename", file.getFilename());
            return "/share/link";
        }
        map.put("msg","密码错误");
        map.put("url",url);
        return "/share/links";
    }

    //下载
    @RequestMapping("/download")
    public void download(Integer id, HttpServletResponse resp, HttpSession session) throws Exception {
        ShareFileLinkInfo info = linkInfoService.getLinkInfoById(id);
        File file = fileService.getFileByFileId(info.getFileid());
        String name = file.getFilename();
        // 下载时文件名会乱码或不显示，进行转码
        String downloadFielName = new String(name.getBytes("UTF-8"), "iso-8859-1");
        // 设置响应的内容类型为流的方式
        resp.setContentType("application/octet-stream");
        // 让服务器告诉浏览器它发送的数据属于什么文件类型（流）
        resp.setHeader("content-type", "application/octet-stream");
        // 告诉浏览器这个文件的类型和名字(attachment--以附件的方式)
        resp.setHeader("Content-Disposition", "attachment;filename=" + downloadFielName);

        // 以流的方式将文件从真实的存储地址读回来--内存
        FileInputStream fis = new FileInputStream(file.getLocal() + java.io.File.separator + name);
        ServletOutputStream os = resp.getOutputStream();
        int len = 0;
        // 自定义缓冲区（缓冲区的大小为1024）
        byte[] b = new byte[1024];
        while ((len = fis.read(b)) != -1) {
            os.write(b, 0, len);
        }
        os.close();
        fis.close();
    }



}
